package com.cqw.common;

import com.cqw.exception.CommonException;
import com.github.pagehelper.Page;
import org.apache.commons.collections.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-05-26 17:46
 * @Description:
 */
public class PageableEntitiesConverter {


    /**
     * 将model转成co
     *
     * @param models
     * @param converter
     * @param <M>
     * @param <V>
     * @return
     */
    public static <M, V> List<V> toVos(List<M> models, ViewObjectConverter<M, V> converter) {
        if (converter == null) {
            throw new CommonException("没有传入实体数据转化器");
        }

        if (CollectionUtils.isEmpty(models)) {
            return Collections.emptyList();
        }

        //根据自定义逻辑对数据进行转换
        List<V> vos = converter.toVos(models);
        //如果使用的数据库的自动分页，将分页信息复制出来
        if (models instanceof Page) {
            Page page = (Page) models;

            Page<V> pageVos = new Page<>();
            pageVos.setTotal(page.getTotal());
            pageVos.setPageSize(page.getPageSize());
            pageVos.setPageNum(page.getPageNum());
            pageVos.addAll(vos);
            return pageVos;
        }
        return vos;
    }


    /**
     * 将model获取的结果转为Page对象
     *
     * @param models
     * @param <V>
     * @return
     */
    public static <V> Page<V> toPageEntities(List<V> models) {
        Page<V> pageVos = new Page<>();
        if (models instanceof Page) {
            Page page = (Page) models;
            pageVos.setTotal(page.getTotal());
            pageVos.setPageSize(page.getPageSize());
            pageVos.setPageNum(page.getPageNum());
            pageVos.addAll(models);
        }
        return pageVos;


    }


}
